import React, { useState, useRef, useEffect } from "react";
import TodoList from "./TodoList";
import {v4 as uuidV4} from 'uuid'
// react manages states in app => state chages, then re-render
// hook:
// useState: return an array, specifically, [array, function]
// useRef: reference elements inside HTML
// useEffect: define a function to do things when argument passed into useEffect() changes
function App() {
const LOCAL_STORAGE_KEY = "TODOS"
// * Object destructuring
const [todos, setTodos] = useState([])
// ^^^^^^^^ argument is the initial state
// ^^^^^^^ function to update `todos`
// ^^^^^ array that return by useState()
const todoTitleRef = useRef()
useEffect(() => {
console.log("loadItem()")
console.log(localStorage.getItem(LOCAL_STORAGE_KEY))
const localTodos = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY))
if (localTodos) {
setTodos((previousTodo) => {
return [...previousTodo, ...localTodos]
})
}
}, [])
// ^^ pass an empty array, then it will run exactly once
// since the empty array will not change
useEffect(() => {
console.log("setItem()")
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(todos))
}, [todos])
function handleAddTodo(e) {
const title = todoTitleRef.current.value
if (title === "") return
setTodos((previousTodo) => {
return [...previousTodo, {id: uuidV4(), title: title, completed: false}]
})
todoTitleRef.current.value = ""
} // handleAddTodo()
function toggleTodo(id) {
// make a copy of current todos
const newTodos = [...todos]
const toBeToggled = newTodos.find((todo) => todo.id === id)
toBeToggled.completed = !toBeToggled.completed
setTodos(newTodos)
}
return (
<>
<TodoList todos={todos} toggleTodo={toggleTodo} />
{/* every components has `props` */}
<input type="text" ref={todoTitleRef} />
<input type="button" value="Add Todo" onClick={handleAddTodo}/>
<input type="button" value="Clear Completed" />
<p>0 left to do</p>
</>
);
}
export default App;